package com.physics.mps.common.util;

import cn.hutool.jwt.JWTUtil;
import com.physics.mps.common.config.constant.JWTConstants;
import com.physics.mps.entity.enums.CodeEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.StringUtils;


/**
 * @author mcsoft
 * @date 2023/8/28 14:51
 */
@Log4j2
public class LoginUtil {



    protected final static ThreadLocal<String> TOKEN = new ThreadLocal<>();

    protected final static ThreadLocal<Integer> USERID = new ThreadLocal<>();

    protected final static ThreadLocal<String> USERNAME = new ThreadLocal<>();


    protected void remove() {
        TOKEN.remove();
        USERID.remove();
        USERNAME.remove();
    }


    /**
     * token获取用户名
     *
     * @return
     */
    public static String getUsername() {
        try {
            String username = USERNAME.get();
            if (StringUtils.isEmpty(username)) {
                username = JWTUtil.parseToken(TOKEN.get()).getPayload(JWTConstants.USERNAME).toString();
                USERNAME.set(username);
            }
            return username;
        } catch (Exception e) {
            log.info("获取登录用户ID异常：{}", e.getMessage());
            return null;
        }
    }


    /**
     * token获取用户ID
     *
     * @return
     */
    public static Integer getUserId() {
        try {
            Integer userId = USERID.get();
            if (null == userId) {
                userId = Integer.valueOf(JWTUtil.parseToken(TOKEN.get()).getPayload(JWTConstants.USER_ID).toString());
                USERID.set(userId);
            }
            return userId;
        } catch (Exception e) {
            log.info("获取登录用户ID异常：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取 Token
     *
     * @return Token
     */
    public static String getToken() {
        String token = TOKEN.get();
        AssertUtil.isBlank(token, CodeEnum.LOGIN_TOKEN_NOT_EMPTY);
        return token;
    }

    public static void setToken(String token) {
        TOKEN.set(token);
    }

    public static void removeAll() {
        TOKEN.remove();
        USERID.remove();
        USERNAME.remove();
    }


    /**
     * 根据token获取用户ID
     *
     * @param token
     * @return
     */
    public static Integer getUserId(String token) {
        try {
            return Integer.valueOf(JWTUtil.parseToken(token).getPayload(JWTConstants.USER_ID).toString());
        } catch (Exception e) {
            log.info("获取登录用户ID异常, {}", token, e);
            return null;
        }
    }



}
